package com.xianyun.book.event.handler;

import com.alibaba.cola.catchlog.CatchAndLog;
import com.alibaba.cola.dto.Response;
import com.alibaba.cola.exception.BizException;
import com.xianyun.book.api.BookServiceI;
import com.xianyun.book.common.core.event.EventHandler;
import com.xianyun.book.common.core.event.EventHandlerI;
import com.xianyun.book.domain.book.Book;
import com.xianyun.book.domain.book.BookStatus;
import com.xianyun.book.domain.gateway.BookGateway;
import com.xianyun.book.dto.BookUpdateCmd;
import com.xianyun.book.dto.domainevent.BookTransactionEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Date;


/**
 * 用户交易事件
 * @author ytt
 */
@CatchAndLog
@Slf4j
@EventHandler
public class BookTransactionHandler implements EventHandlerI<Response, BookTransactionEvent> {

    @Autowired
    private BookServiceI bookService;

    @Autowired
    private BookGateway bookGateway;

    /**
     * 用户交易事件
     * @param event 用户交易事件
     * @return 响应结果
     */
    @Override
    public Response execute(BookTransactionEvent event) {
        log.info("产生交易信息正在刷新库存信息 需要更改的书籍ISBN:{}",event.getIsbn());
        if (bookService.getBookInfoByIsbn(event.getIsbn()).isSuccess()){
            Book searchBook = bookGateway.saveOrQueryBookByIsbn(event.getIsbn());
            BookUpdateCmd bookUpdateCmd = initBookUpdateCmd(searchBook);
            event.setUserSecurity(event.getUserSecurity());
            if (event.isBuyer()){
                if (bookUpdateCmd.getInSellNumber() - event.getBookNumber()<=0){
                    bookUpdateCmd.setBookStatus(BookStatus.SOLD_OUT.getStatusId());
                    log.info("该ISBN:{}--对应的的书籍已售空，请及时加价收购！",event.getIsbn());
                }
            }else {
                if (bookUpdateCmd.getInSellNumber() + event.getBookNumber() >= 0){
                    bookUpdateCmd.setBookStatus(BookStatus.IN_SALE.getStatusId());
                    bookUpdateCmd.setNewDate(new Date());
                    log.info("该ISBN:{}--对应的的书籍已上新，可进行推送！",event.getIsbn());
                }
            }
            bookService.refreshBookInfo(bookUpdateCmd);
            return Response.buildSuccess();
        }else {
            throw new BizException("该书籍不存在请先填写书籍详细");
        }
    }

    private BookUpdateCmd initBookUpdateCmd(Book book){
        BookUpdateCmd updateCmd = new BookUpdateCmd();
        BeanUtils.copyProperties(book,updateCmd);
        updateCmd.setOriginalPrice(book.getPrice());
        updateCmd.setBookStatus(book.getBookStatus().getStatusId());
        updateCmd.setInSellNumber(book.countInSellerNumber());
        return updateCmd;
    }
}
